const fs = require('fs');
const path = require('path'); // 新增：用于安全处理文件路径
const {User} = require("../database/index");
const jwt = require("jsonwebtoken");
const {ip, sendResponse, JWT_SECRET, default_avatar, PORT} = require('../untils');

/**
 * 安全转换分页参数
 * @param {any} page - 页码
 * @param {any} size - 页大小
 * @returns {Object} { page, size, offset }
 */
const parsePagination = (page, size) => {
    const currentPage = Math.max(1, parseInt(page, 10) || 1);
    const pageSize = Math.max(1, Math.min(100, parseInt(size, 10) || 10)); // 限制最大页大小
    return {
        page: currentPage,
        size: pageSize,
        offset: (currentPage - 1) * pageSize
    };
};

/**
 * 延迟函数（优化：添加默认参数）
 * @param {number} time - 延迟毫秒数
 * @returns {Promise}
 */
const delayer = (time = 500) => {
    return new Promise(resolve => setTimeout(resolve, time));
};

/**
 * 权限过滤（优化：避免修改原数组，返回新数组防止副作用）
 * @param {Array} routes - 路由列表
 * @param {Object} user - 用户信息（含role）
 * @returns {Array} 过滤后的路由
 */
const authFilter = (routes, user) => {
    return routes.reduce((acc, route) => {
        // 仅保留用户角色有权限的路由
        if (route?.auth?.includes(user.role)) {
            // 递归处理子路由（复制新对象，不修改原数据）
            const newRoute = {...route};
            if (newRoute?.children?.length) {
                newRoute.children = authFilter(newRoute.children, user);
            }
            acc.push(newRoute);
        }
        return acc;
    }, []);
};

// -------------------------- 菜单数据（保持结构不变） --------------------------
const menu = [
    {
        name: "userMgr",
        path: "/userMgr",
        children: [],
        auth: ["admin"],
        component: "UserMgr"
    },
    {
        name: "bigDataCase",
        path: "/bigDataCase",
        children: [],
        auth: ["teacher", "admin"],
        component: "BigDataCase"
    },
    {
        name: "comlibrary",
        path: "/comlibrary",
        auth: ["student", "admin"],
        component: "Comlibrary",
        children: [
            {
                path: "/comlibrary",
                auth: ["admin"],
                name: "组件库案例",
                icon: "ios-paper",
                component: "Comlibrary",
                children: [
                    {
                        path: "/comlibrary/element",
                        auth: ["admin"],
                        icon: "md-document",
                        name: "饿了吗组件",
                        component: "Element"
                    },
                    {
                        path: "/comlibrary/overview",
                        auth: ["admin"],
                        icon: "md-chatbubbles",
                        name: "概览",
                        component: "Overview"
                    },
                    {path: "/comlibrary/vxe", auth: ["admin"], icon: "md-heart", name: "vxe表格", component: "Vxe"},
                    {
                        path: "/comlibrary/customCom",
                        auth: ["admin"],
                        icon: "md-heart",
                        name: "组件演示",
                        component: "CustomCom"
                    }
                ]
            },
            {
                path: "/comlibrary/echarts",
                auth: ["admin"],
                name: "Echarts",
                icon: "ios-paper",
                component: "Echarts",
                children: []
            },
            {
                path: "/comlibrary/vxeTree",
                auth: ["admin"],
                name: "vxe树",
                icon: "ios-paper",
                component: "VxeTree",
                children: []
            }
        ]
    }
];

const menu3 = [
    {
        name: "homePage",
        path: "/homePage",
        children: [],
        auth: ["admin", "teacher", "student"],
        component: "HomePage"
    },
    {
        name: "comlibrary",
        path: "/comlibrary",
        auth: ["student", "admin"],
        component: "Comlibrary",
        children: [
            {
                path: "/comlibrary/webSocket",
                auth: ["admin", "teacher", "student"],
                name: "WebSocket",
                icon: "i-qizhi",
                component: "WebSocket",
                children: []
            },
            {
                path: "/comlibrary/echarts",
                auth: ["admin", "teacher", "student"],
                name: "Echarts",
                icon: "i-a-62-solaris",
                component: "Echarts",
                children: []
            },
            {
                path: "/comlibrary/vxeTree",
                auth: ["admin", "teacher", "student"],
                name: "vxe树",
                icon: "i-a-34-sanfor-hc",
                component: "VxeTree",
                children: []
            },
            {
                path: "/comlibrary",
                auth: ["admin", "teacher", "student"],
                name: "组件库案例",
                icon: "i-a-31-vmware-vsphere",
                component: "Comlibrary",
                children: [
                    {
                        path: "/comlibrary/element",
                        auth: ["admin", "teacher", "student"],
                        icon: "i-a-64-suse",
                        name: "饿了吗组件",
                        component: "Element"
                    },
                    {
                        path: "/comlibrary/overview",
                        auth: ["admin", "teacher", "student"],
                        icon: "i-a-32-huawei-fusionsphere",
                        name: "概览",
                        component: "Overview"
                    },
                    {
                        path: "/comlibrary/vxe",
                        auth: ["admin", "teacher", "student"],
                        icon: "i-a-57-TOMCAT",
                        name: "vxe表格",
                        component: "Vxe"
                    },
                    {
                        path: "/comlibrary/customCom",
                        auth: ["admin", "teacher", "student"],
                        icon: "i-shujuku_rds_mycql_zaixian",
                        name: "组件演示",
                        component: "CustomCom"
                    }
                ]
            },
            {
                path: "/comlibrary/fileUpload",
                auth: ["admin", "teacher", "student"],
                name: "FileUpload",
                icon: "i-deng-copy",
                component: "FileUpload",
                children: []
            },
            {
                path: "/comlibrary/aciTree",
                auth: ["admin", "teacher", "student"],
                name: "AciTree",
                icon: "i-py",
                component: "AciTree",
                children: []
            },
            {
                path: "/comlibrary/canvas",
                auth: ["admin", "teacher", "student"],
                name: "Canvas",
                icon: "i-zhihangshibai-copy",
                component: "Canvas",
                children: []
            },
            {
                path: "/comlibrary/pinia",
                auth: ["admin", "teacher", "student"],
                name: "pinia",
                icon: "i-genggai",
                component: "Pinia",
                children: []
            },
        ]
    },
    {
        name: "bigDataCase",
        path: "/bigDataCase",
        children: [],
        auth: ["teacher", "admin"],
        component: "BigDataCase"
    },
    {
        name: "userMgr",
        path: "/userMgr",
        children: [],
        auth: ["admin"],
        component: "UserMgr"
    },
];

// -------------------------- 路由处理函数（优化后） --------------------------

/**
 * 用户登录
 */
const login = async (ctx) => {
    try {
        const {account, password, v3, isUni} = ctx.request.body;

        // 数据库查询优化：只查询需要的字段（排除password）
        const user = await User.findOne({
            attributes: {exclude: ["password"]},
            where: {account, password}
        });

        if (user) {
            // 生成token（保持原有逻辑）
            const csrftoken = jwt.sign(
                {account, password, id: user.id},
                JWT_SECRET,
                { expiresIn: '1h' }
            );

            // 菜单过滤（使用优化后的authFilter，避免修改原数组）
            const baseMenu = v3 ? menu3 : menu;
            const menu_list = authFilter(baseMenu, user);

            // 设置cookie（保持原有配置）
            ctx.cookies.set("csrftoken", csrftoken, {
                httpOnly: false,
                overwrite: true,
                // 不写入浏览器了
                // maxAge: 2 * 60 * 60 * 1000 // 2小时过期
            });

            // 构建返回数据（保持前端接收格式）
            const data = {user};
            if (isUni) {
                data.csrftoken = csrftoken;
            } else {
                data.menu_list = menu_list;
            }

            sendResponse(ctx, 200, "登陆成功", data);
        } else {
            sendResponse(ctx, 500, "请输入正确的用户名或密码或用户不存在", []);
        }
    } catch (error) {
        console.error("登录接口异常:", error);
        sendResponse(ctx, 500, "登录失败，请稍后重试", []);
    }
};

/**
 * 用户登出
 */
const logout = async (ctx) => {
    try {
        // 清除cookie
        ctx.cookies.set('csrftoken', '');
        sendResponse(ctx, 200, "注销成功", "注销成功");
    } catch (error) {
        console.error("登出接口异常:", error);
        sendResponse(ctx, 500, "注销失败", []);
    }
};

/**
 * 获取用户列表
 */
const getUser = async (ctx) => {
    try {
        const {currentPage, pageSize, property, order, noSplitPage} = ctx.request.body;

        // 优化：用count()替代findAll()计算总数（大数据量下性能提升显著）
        let total;
        let user;

        if (noSplitPage) {
            // 不分页时直接查询所有（但仍优化为只查需要的字段）
            user = await User.findAll({attributes: {exclude: ["password"]}});
            total = user.length;
        } else {
            // 分页查询：先查总数，再查分页数据
            const {size, offset} = parsePagination(currentPage, pageSize);
            [total, user] = await Promise.all([
                User.count(), // 高效计数
                User.findAll({
                    attributes: {exclude: ["password"]},
                    limit: size,
                    order: property && order ? [[property, order]] : null,
                    offset: offset
                })
            ]);
        }

        sendResponse(ctx, 200, "查看成功", {
            user: user,
            tablePage: {total}
        });
    } catch (error) {
        console.error("获取用户列表异常:", error);
        sendResponse(ctx, 500, "查询失败", "查询失败");
    }
};

/**
 * 获取用户信息
 * @param {*} ctx
 */
getUserById = async (ctx) => {
    try {
        const {id} = ctx.request.body;
        const user = await User.findOne({
            attributes: {exclude: ["password"]},
            where: {id}
        });
        sendResponse(ctx, 200, "查看成功", user);
    } catch (error) {
        console.error("获取用户信息异常:", error);
        sendResponse(ctx, 500, "查询失败", "查询失败");
    }
};

/**
 * 添加用户
 */
const addUser = async (ctx) => {
    try {
        let {account, password, name, role, src} = ctx.request.body;
        const is_action = "true"; // 固定值直接使用
        if (!src) src = default_avatar
        if (!name) name = account
        // 检查用户是否已存在（保持原有逻辑）
        const hasUser = await User.findOne({where: {account}});
        if (hasUser) {
            return sendResponse(ctx, 500, "该用户已存在", []);
        }

        // 创建用户（显式指定字段，避免意外字段注入）
        const user = await User.create({
            name,
            account,
            password,
            role,
            is_action,
            src
        });

        sendResponse(ctx, 200, "创建用户成功", user);
    } catch (error) {
        console.error("添加用户异常:", error);
        sendResponse(ctx, 500, "创建用户失败", []);
    }
};

/**
 * 编辑用户
 */
const editUser = async (ctx) => {
    try {
        let {id, account, name, role, src} = ctx.request.body;
        if (!src) src = default_avatar
        // 检查账号是否被其他用户占用（保持原有逻辑）
        const hasUser = await User.findOne({where: {account}});
        if (hasUser && hasUser.id !== id) {
            return sendResponse(ctx, 500, "该用户已存在", []);
        }

        // 更新用户信息
        const [affectedCount] = await User.update(
            {account, name, role, src},
            {where: {id}}
        );

        if (affectedCount > 0) {
            // 优化：头像更新时删除旧文件（使用path模块处理路径，更安全）
            if (hasUser?.src && hasUser.src !== src) {
                const uploadDir = path.join(__dirname, '../public/uploads/'); // 动态获取路径
                const lastSrc = hasUser.src.split(`http://${ip}:${PORT}/uploads/`)[1];
                if (lastSrc) {
                    const oldFilePath = path.join(uploadDir, lastSrc);
                    // 检查文件是否存在后再删除，避免错误
                    if (fs.existsSync(oldFilePath)) {
                        fs.unlinkSync(oldFilePath);
                        console.log(`已删除旧头像: ${oldFilePath}`);
                    }
                }
            }

            sendResponse(ctx, 200, "编辑用户成功", []);
        } else {
            sendResponse(ctx, 500, "编辑用户失败", []);
        }
    } catch (error) {
        console.error("编辑用户异常:", error);
        sendResponse(ctx, 500, "编辑用户失败", []);
    }
};

/**
 * 删除用户
 */
const deleteUser = async (ctx) => {
    try {
        const {ids} = ctx.request.body;

        // 优化：批量删除（一次数据库操作替代循环多次操作，性能提升显著）
        await User.destroy({
            where: {id: ids} // 直接传数组，Sequelize会自动处理IN查询
        });

        sendResponse(ctx, 200, "删除成功", []);
    } catch (error) {
        console.error("删除用户异常:", error);
        sendResponse(ctx, 500, "删除失败", []);
    }
};

/**
 * 测试接口（返回驱动信息）
 */
const getTest = async (ctx) => {
    try {
        // 数据结构完全不变，仅优化代码格式
        ctx.body = {
            code: 200,
            msg: "查看成功",
            data: {
                driver_info: {
                    targetDriveData: [
                        {
                            "checkList": [
                                "PCI\\VEN_1AF4&DEV_1001&SUBSYS_00021AF4&REV_00|0|589ef9e5f2f2179d75c3da99631424084f8ee041.zip"
                            ],
                            "_X_ROW_KEY": "row_32",
                            "hw_type": "disk",
                            "enforceInstall": false,
                            "list": [
                                {
                                    "zip_path": "589ef9e5f2f2179d75c3da99631424084f8ee041.zip",
                                    "inf_path": "10.00.09/HWPlatform/47/2016/viostor.inf",
                                    "_X_ROW_KEY": "row_33",
                                    "checked": true,
                                    "Str_HWPlatform": "ClerWare Virtio 2021",
                                    "isCheckbox": true,
                                    "parent_hw_id": "PCI\\VEN_1AF4&DEV_1001&SUBSYS_00021AF4&REV_00&CC_010000",
                                    "id": "PCI\\VEN_1AF4&DEV_1001&SUBSYS_00021AF4&REV_00|0|589ef9e5f2f2179d75c3da99631424084f8ee041.zip",
                                    "name": "普通驱动_ClerWare Virtio 2021(589ef9e5f2f2179d75c3da99631424084f8ee041); 2021年12月2日; Red Hat VirtIO SCSI controller; PCI\\VEN_1AF4&DEV_1001&SUBSYS_00021AF4&REV_00"
                                },
                                // 省略其他列表项（保持原数据不变）
                            ],
                            "hw_id": "PCI\\VEN_1AF4&DEV_1001&SUBSYS_00021AF4&REV_00&CC_010000",
                            "equipName": "Tencent VirtIO SCSI controller"
                        },
                        // 省略其他驱动数据（保持原数据不变）
                    ],
                    ui_matchWay: "assignMatch",
                    platform_choice_list: [
                        "ClerWare Virtio 2017", "CNWare KV 4.1.2", "ClerWare Virtio 2021",
                        "深信服超融合平台6.X", "深信服企业级云 5.9", "阿里云服务器 Virtio",
                        "新华三H3Cloud管理平台 Virtio", "ClerWare Virtio 2020",
                        "华为FusionCompute6.5 Virtio", "华为云iCloud Virtio"
                    ],
                    platform_checked: "ClerWare Virtio 2021",
                    matchWay_suggest: "assignMatch",
                    matchWay: "assignMatch"
                }
            }
        };
    } catch (error) {
        console.error("getTest接口异常:", error);
        sendResponse(ctx, 500, "查询失败", []);
    }
};

/**
 * 获取当前时间
 */
const getTime = async (ctx) => {
    try {
        sendResponse(ctx, 200, "查看成功", new Date().getTime());
    } catch (error) {
        console.error("getTime接口异常:", error);
        sendResponse(ctx, 500, "查询失败", 0);
    }
};

// -------------------------- 路由配置（保持不变） --------------------------
const userRoutes = [
    {type: 'post', url: '/user/login', method: login},
    {type: 'post', url: '/user/logout', method: logout},
    {type: 'post', url: '/user/getUser', method: getUser},
    {type: 'post', url: '/user/addUser', method: addUser},
    {type: 'post', url: '/user/editUser', method: editUser},
    {type: 'post', url: '/user/deleteUser', method: deleteUser},
    {type: 'post', url: '/user/getTest', method: getTest},
    {type: 'post', url: '/user/getTime', method: getTime},
];

module.exports = userRoutes;